//
//  UIApplication+topViewController.swift
//  GuessingRiddles
//
//  Created by 灵工邦 on 2024/5/28.
//

import UIKit

extension UIApplication {
    
    // 获取最上层的视图控制器
    class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }
        
        if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
            return topViewController(base: selected)
        }
        
        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }
        
        return base
    }
}

// 判断最上层控制器是否是某个特定控制器
func isTopViewController(_ viewController: UIViewController.Type) -> Bool {
    if let topVC = UIApplication.topViewController() {
        return topVC.isKind(of: viewController)
    }
    return false
}
